package com.cqrcb.cloud.config.log;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.MDC;
import org.springframework.util.StringUtils;

import com.cqrcb.cloud.config.annotation.*;

import java.util.UUID;

/**
 * 日志拦截器
 * @author binbin.hou
 * @date 2018/12/7
 */
@Aspect
public class LogAspect {

    public final static String TRACE_ID = "traceId";

    /**
     * 拦截入口下所有的 public方法
     */
//    @Pointcut("@annotation(com.cqrcb.cloud.config.annotation.DistributedLog)")
//    public void pointCut(){}

//    @Pointcut("execution(public * com.cqrcb.cloud.controller..*(..))")
//    public void pointCut() {
//    }

    /**
     * 拦截处理
     *
     * @param point point 信息
     * @return result
     * @throws Throwable if any
     */
//    @Around("pointCut()")
    @Around("@annotation(log)")
    public Object around(ProceedingJoinPoint point,CustomLogAnnotation log) throws Throwable {
        String feignId = MDC.get("feignId");
        //添加 MDC
//        String traceId = MDC.get(DubboConstants.TRACE_ID);
        if(!StringUtils.isEmpty(feignId)){
            MDC.put(TRACE_ID,feignId);
        }else{
            MDC.put(TRACE_ID, getUUID());
        }
        Object result = null;
        try {
            result = point.proceed();
        }finally {
            //移除 MDC
            MDC.remove(TRACE_ID);
        }
        return result;
    }

    /**
     * 获取UUID
     *
     * @return String UUID
     */
    public String getUUID() {
        String uuid = UUID.randomUUID().toString();
        //替换-字符
        return uuid.replaceAll("-", "");
    }
}
